<template>
  <el-form label-position="right" label-width="100px" label-suffix=":">
    <el-form-item label="执行动作">
      <el-select v-model="localData[fields.type]" @change="handleRemoteTypeChange" clearable @clear="handleRemoteTypeChange">
        <el-option v-for="opt in typeOptions || remoteTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="选择模型" v-if="getTypeLabel(localData[fields.type]) == '模型接口调用'">
      <el-select v-model="localData[fields.ajaxModel]" filterable clearable @change="generateUrlByAjaxModelApi">
        <el-option v-for="opt in ajaxModelList" :key="opt.tableName" :label="`${opt.description}(${opt.tableName})`" :value="opt.tableName" />
      </el-select>
    </el-form-item>
    <el-form-item label="选择方法" v-if="getTypeLabel(localData[fields.type]) == '模型接口调用'">
      <el-select v-model="localData[fields.ajaxApi]" filterable clearable @change="generateUrlByAjaxModelApi">
        <el-option v-for="opt in ajaxApiList" :key="opt.dictValue" :label="`${opt.dictLabel}(${opt.dictValue})`" :value="opt.dictValue" />
      </el-select>
    </el-form-item>
    <el-form-item label="url" v-if="localData[fields.type]">
      <el-input v-if="getTypeLabel(localData[fields.type]) == '本地接口调用'" v-model="localData[fields.url]" placeholder="请输入url"> </el-input>
      <el-tag v-else-if="getTypeLabel(localData[fields.type]) == '模型接口调用'">{{ localData[fields.url] }}</el-tag>
      <api-selector v-else v-model="localData[fields.url]" />
    </el-form-item>
    <el-form-item label="请求方式" v-if="getTypeLabel(localData[fields.type]) == '本地接口调用'">
      <el-radio-group v-model="localData[fields.method]">
        <el-radio-button label="POST" value="post" />
        <el-radio-button label="GET" value="get" />
      </el-radio-group>
    </el-form-item>
    <el-form-item label="请求体类型" v-if="getTypeLabel(localData[fields.type]) == '本地接口调用'">
      <el-radio-group v-model="localData[fields.contentType]">
        <el-radio-button label="FormData" value="formData" />
        <el-radio-button label="RawJSON" value="rawJson" />
      </el-radio-group>
    </el-form-item>
    <el-form-item label="请求头">
      <anvil-dynamic v-model="localData[fields.headers]" :children="option" />
    </el-form-item>
    <el-form-item label="参数设置">
      <el-tag>{{ paramsSettedTag }}</el-tag>
      <text-edit-button text="编辑参数" @click="showParamsSetting = true" />
      <!-- 请求体:
      <anvil-dynamic v-model="localData[fields.params]" :children="option" /> -->
    </el-form-item>
    <el-form-item label="执行前钩子">
      <el-select v-model="localData[fields.hookBefore]" filterable clearable>
        <el-option v-for="opt in getPageFuncs()" :key="opt.funcName" :label="opt.funcLabel" :value="opt.funcName" />
      </el-select>
    </el-form-item>
    <el-form-item label="执行后钩子">
      <el-select v-model="localData[fields.hookAfter]" filterable clearable>
        <el-option v-for="opt in getPageFuncs()" :key="opt.funcName" :label="opt.funcLabel" :value="opt.funcName" />
      </el-select>
    </el-form-item>
    <el-form-item label="关闭遮罩层">
      <el-switch v-model="localData[fields.noLoading]" />
    </el-form-item>
  </el-form>
  <params-setting v-if="showParamsSetting" v-model="showParamsSetting" :data="localData[fields.params]" :fields="compFields" :options="options" @submit="handleParamsSubmit" />
</template>

<script>
import { searchAll } from '@base/api/base/dict/type';
import { searchAllMda } from '@uni/api/uni/mda/table/info';
import paramsSetting from './paramsSetting.vue';

export default {
  name: 'CustomAjaxSetting',
  components: { paramsSetting },
  props: {
    modelValue: {
      type: Object,
      default: () => {}
    },
    options: {
      type: Object,
      default: () => {}
    },
    // 字段映射配置
    props: {
      type: Object,
      default: () => {
        return {};
      }
    },
    // 执行动作类型
    typeOptions: {
      type: Array,
      default: undefined
    }
  },
  data() {
    return {
      localData: {},
      ajaxModelList: [],
      ajaxApiList: [],
      showParamsSetting: false,
      paramsSettedTag: '',
      // 接收值替换时，label不可换，value可以替换
      remoteTypeOptions: [
        {
          label: '注册接口调用',
          value: 'ajax'
        },
        {
          label: '模型接口调用',
          value: 'ajaxModel'
        },
        {
          label: '本地接口调用',
          value: 'ajaxLocal'
        }
      ],
      option: {
        column: [
          {
            type: 'input',
            prop: 'key',
            label: 'key'
          },
          {
            type: 'input',
            prop: 'value',
            label: 'value'
          }
        ]
      }
    };
  },
  computed: {
    baseUrl() {
      return import.meta.env.VITE_APP_BASE_API;
    },
    // 处理字段映射
    fields() {
      if (this.props) {
        return {
          type: this.props.type || 'type',
          ajaxModel: this.props.ajaxModel || 'ajaxModel',
          ajaxApi: this.props.ajaxApi || 'ajaxApi',
          url: this.props.url || 'url',
          method: this.props.method || 'method',
          contentType: this.props.contentType || 'contentType',
          headers: this.props.headers || 'headers',
          params: this.props.params || 'params',
          hookBefore: this.props.hookBefore || 'hookBefore',
          hookAfter: this.props.hookAfter || 'hookAfter',
          noLoading: this.props.noLoading || 'noLoading'
        };
      } else {
        return {};
      }
    },
    compFields() {
      return this.getCallableCompList(this.options);
    }
    // 判断是否设置了参数,返回文本
    // isParamsSetted() {
    //   if (this.localData[this.fields.params] && Object.keys(this.localData[this.fields.params]).length) {
    //     const { constantParams, compParams, withFormData } = this.localData[this.fields.params];
    //     let strArr = [];
    //     if (constantParams && constantParams.lenghth) {
    //       strArr.push('常量参数');
    //     }
    //     if (compParams && compParams.lenghth) {
    //       strArr.push('组件参数');
    //     }
    //     if (withFormData) {
    //       strArr.push('表单数据');
    //     }
    //     return strArr.join(',');
    //   } else {
    //     return '未设置';
    //   }
    // }
  },
  watch: {
    modelValue: {
      handler(newVal) {
        this.localData = newVal;
      },
      immediate: true,
      deep: true
    },
    localData: {
      handler(newVal) {
        this.$emit('update:modelValue', newVal);
      },
      deep: true
    }
  },
  mounted() {
    this.searchAjaxModel();
    this.searchAjaxApi();
    this.getParamsSettedTag();
  },
  methods: {
    getParamsSettedTag() {
      this.paramsSettedTag = this.isParamsSetted();
    },
    getPageFuncs() {
      return this.options.funcs ?? [];
    },
    searchAjaxModel() {
      return searchAllMda({isEnable:'Y'}).then((res) => {
        this.ajaxModelList = res.data;
      });
    },
    searchAjaxApi() {
      this.getDicts('uni_mda_rest').then((response) => {
        this.ajaxApiList = response.data;
      });
    },
    generateUrlByAjaxModelApi() {
      this.localData[this.fields.url] = `/uni/mda/${this.localData[this.fields.ajaxModel]}/${this.localData[this.fields.ajaxApi]}`;
    },
    handleRemoteTypeChange(value) {
      this.localData[this.fields.url] = '';
      if (this.localData[this.fields.type] == 'ajaxModel') {
        this.generateUrlByAjaxModelApi();
      } else if (this.localData[this.fields.type] == 'ajaxLocal') {
        this.localData[this.fields.url] = this.baseUrl;
        this.localData[this.fields.method] = 'post';
        this.localData[this.fields.contentType] = 'formData';
      }
    },
    getTypeLabel(value) {
      if (this.typeOptions && this.typeOptions.length) {
        return this.typeOptions.find((item) => item.value === value)?.label;
      } else {
        return this.remoteTypeOptions.find((item) => item.value === value)?.label;
      }
    },
    handleParamsSubmit(data) {
      for (let key in data) {
        this.localData[this.fields.params][key] = data[key];
      }
      this.getParamsSettedTag();
    },
    isParamsSetted() {
      if (this.localData[this.fields.params] && Object.keys(this.localData[this.fields.params]).length) {
        const { contantParams, compParams, withFormData } = this.localData[this.fields.params];
        const strArr = [];
        if (contantParams && contantParams.length) {
          strArr.push('常量参数');
        }
        if (compParams && compParams.length) {
          strArr.push('组件参数');
        }
        if (withFormData) {
          strArr.push('表单数据');
        }

        return strArr.length ? strArr.join(',') : '未设置';
      } else {
        return '未设置';
      }
    }
  }
};
</script>

<style></style>
